#include <stdlib.h>
#include <math.h>

#include "endpoint.h"

float energy_compute(const int16_t *data)
{
	uint32_t i;
	float cdata_float = 0.0;
	float out = 0.0;
	for (i = 0; i < FRAME_LEN_ENDPOINT; i++) {
		cdata_float = ((float)(data[i]) / (float)(1<<15));
		out += (cdata_float * cdata_float);
	}
	return out;
}

uint32_t start_endpoint_detection(EP_DETECT_STR *ep_detect_struct, const int16_t *audio_data)
{
 	volatile float Hi;
	uint16_t end_gap_num = 0, start_gap_num = 0;
	Hi = energy_compute(audio_data);
	// printf("%f\r\n", Hi);
	if (ep_detect_struct->start_flag == 0)
	{
		/* 判断当前帧和静音帧差值是否大于阈值 */
		if (fabs(Hi - ep_detect_struct->energy_average) >= POINT_THREADHOLD)
		{
			ep_detect_struct->start_num++;
			start_gap_num = 0;
			/* 判断连续有效帧数量是否大于起始帧数 */
			if (ep_detect_struct->start_num >= START_NUM_THREADHOLD)
			{
				ep_detect_struct->start_flag = 1;
				return GET_START_POINT;
			}
		} else {
			start_gap_num++;
			if (start_gap_num >= NUM_START_GAP)
			{
				ep_detect_struct->start_num = 0;
			}
		}
	} else if (fabs(Hi - ep_detect_struct->energy_average) < POINT_THREADHOLD)
			{
				end_gap_num=0;
				ep_detect_struct->end_num++;
				if (ep_detect_struct->end_num >= END_NUM_THREADHOLD)
				{
					ep_detect_struct->start_flag = 0;
					ep_detect_struct->start_num = 0;
					ep_detect_struct->end_num = 0;
					return GET_END_POINT;
				}
			} else {
				end_gap_num++;
				if (end_gap_num > NUM_END_GAP)
				{
					ep_detect_struct->end_num = 0;
				}
			}
	return NO_END_START_POINT;
}
